package com.qqt.csr.common.utils;

import cn.hutool.crypto.digest.HmacAlgorithm;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component("jwtSignerUtil")
public class JwtSignerUtil implements InitializingBean {
    private static final ThreadLocal<JWTSigner> SIGNER_THREAD_LOCAL = new ThreadLocal<>();
    private static final Object LOCK = new Object();
    private static volatile JwtSignerUtil INSTANCE;
    @Value("${socketio.app.security.secretKey}")
    private String imSecretKey;

    @Override
    public void afterPropertiesSet() throws Exception {
        INSTANCE = SpringUtil.getBean(JwtSignerUtil.class);
    }

    /**
     * 获取签名器
     * @return
     */
    public static JWTSigner getSigner() {
        if (SIGNER_THREAD_LOCAL.get() == null) {
            synchronized (LOCK){
                if (SIGNER_THREAD_LOCAL.get() == null) {
                    JWTSigner signer = JWTSignerUtil.createSigner(HmacAlgorithm.HmacSHA256.getValue(), INSTANCE.imSecretKey.getBytes(StandardCharsets.UTF_8));
                    SIGNER_THREAD_LOCAL.set(signer);
                }
                return SIGNER_THREAD_LOCAL.get();
            }
        }
        return SIGNER_THREAD_LOCAL.get();
    }
}
